package cn.juque.datapipeline.controller;

import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import cn.juque.common.base.BaseOperator;
import cn.juque.common.constants.MessageEnum;
import cn.juque.common.exception.AppException;
import cn.juque.common.utils.ValidatorUtil;
import cn.juque.datapipeline.constans.BusinessConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @author juque
 * @version 1.0.0
 * <ul>
 *     <li>BaseController</li>
 * </ul>
 * @date 2023-01-08 15:02:07
 **/
@Slf4j
public class BaseController {

    @Resource
    protected ValidatorUtil validatorUtil;

    /**
     * 解析操作人信息
     *
     * @return BaseOperator
     * @throws AppException AppException
     */
    protected BaseOperator parseOperator() {
        String token = this.requestContextHolder().getHeader(BusinessConstants.TOKEN_HEADER);
        token = CharSequenceUtil.subAfter(token, BusinessConstants.TOKEN_PREFIX, false);
        JWT jwt = JWTUtil.parseToken(token);
        String userId = (String) jwt.getPayload(BusinessConstants.USER_ID);
        if(CharSequenceUtil.isEmpty(userId)) {
            throw new AppException(MessageEnum.NO_LOGIN);
        }
        BaseOperator baseOperator = new BaseOperator();
        baseOperator.setOperatorId(userId);
        return baseOperator;
    }

    /**
     * 获取请求头的值
     * @param key key
     * @return string
     */
    protected String getHeaderValue(String key) {
        if(CharSequenceUtil.isEmpty(key)) {
            return CharSequenceUtil.EMPTY;
        }
        HttpServletRequest servletRequest = this.requestContextHolder();
        return servletRequest.getHeader(key);
    }

    /**
     * 获取会话信息
     *
     * @return HttpServletRequest
     */
    private HttpServletRequest requestContextHolder() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (null == requestAttributes) {
            throw new AppException(MessageEnum.NO_LOGIN.getCode(), MessageEnum.NO_LOGIN.getMsg());
        }
        return ((ServletRequestAttributes) requestAttributes).getRequest();
    }
}
